package com.zhiwang.planet.ui.my

import android.os.Bundle
import android.os.SystemClock
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.bytedance.sdk.openadsdk.AdSlot
import com.bytedance.sdk.openadsdk.TTAdNative
import com.bytedance.sdk.openadsdk.TTAdSdk
import com.bytedance.sdk.openadsdk.TTRewardVideoAd
import com.zhiwang.planet.BuildConfig
import com.zhiwang.planet.R
import com.zhiwang.planet.databinding.ActivityWithDraw2Binding
import com.zhiwang.planet.di.component.DaggerUserComponent
import com.zhiwang.planet.di.module.AccountModule
import com.zhiwang.planet.di.module.AutoDisposeModule
import com.zhiwang.planet.mvp.p.WithDrawPresenter
import com.zhiwang.planet.mvp.v.WithDrawView
import com.zhiwang.planet.mvvm.model.entity.main.WithDrawBody
import com.zhiwang.planet.mvvm.viewmodel.ShareViewModel
import com.zhiwang.planet.mvvm.viewmodel.main.sharedViewModels
import com.zhiwang.planet.mvvm.viewmodel.withdraw.WithDrawViewModel
import com.zhiwang.planet.ui.BaseActivity
import com.zhiwang.planet.ui.RewardAdInteractionListenerAdapter
import com.zhiwang.planet.ui.RewardVideoAdListenerAdapter
import com.zhiwang.planet.ui.my.record.DetailsActivity
import com.zhiwang.planet.ui.my.withdraw.WithDrawRecordActivity
import com.zhiwang.planet.util.Toaster
import com.zhiwang.planet.util.Utils
import com.zhiwang.planet.util.quickStartActivity
import com.zhiwang.planet.widget.SimpleDialogBuilder
import kotlinx.android.synthetic.main.activity_with_draw2.*
import kotlinx.android.synthetic.main.withdraw_sub_item_withdraw.*
import javax.inject.Inject

class WithDrawActivity2 : BaseActivity(), WithDrawView {


    @Inject
    lateinit var viewModel: WithDrawViewModel

    @Inject
    lateinit var withDrawPresenter: WithDrawPresenter

    val shareViewModel by sharedViewModels<ShareViewModel>()


    private lateinit var ttAdNative: TTAdNative
    private lateinit var adVideoSlot: AdSlot

    override fun initInjection() {
        super.initInjection()
        DaggerUserComponent.builder()
                .appComponent(getAppComponent())
                .accountModule(AccountModule(this))
                .autoDisposeModule(AutoDisposeModule(this))
                .build()
                .inject(this)
        withDrawPresenter.withdrawView = this
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = DataBindingUtil.setContentView<ActivityWithDraw2Binding>(this, R.layout.activity_with_draw2)

        setSupportActionBar(toolbar)
        binding.lifecycleOwner = this
        binding.withdrawViewModel = viewModel

        withdraw_rv.layoutManager = GridLayoutManager(this, 4)

        viewModel.load()

        val width = resources.displayMetrics.widthPixels
        val height = resources.displayMetrics.heightPixels
        adVideoSlot = AdSlot.Builder()
                .setCodeId("931608653")
                .setSupportDeepLink(true)
                .setImageAcceptedSize(width, height)
                .build()
        ttAdNative = TTAdSdk.getAdManager().createAdNative(this)

        viewModel.withdrawCash.observe(this, Observer {


            if (BuildConfig.DEBUG){
                withdraw(it,viewModel.checkedIndex.value == 1)
                return@Observer
            }

            if (viewModel.checkedIndex.value == 0)
                playVideoAndWithDraw(it, false)
            else playVideoAndWithDraw(it, true)
        })

        smartRefresh.setOnRefreshListener {
            viewModel.load()
            it.finishRefresh()
        }

        Utils.setStatusBar(this, false, false)
        Utils.setStatusTextColor(true, this)
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.withdraw_detail, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        if (item?.itemId == R.id.menu_withdraw_detail) {
            quickStartActivity(WithDrawRecordActivity::class.java)
        }
        return super.onOptionsItemSelected(item)
    }

    private fun playVideoAndWithDraw(cash: String, isAlipay: Boolean) {

        ttAdNative.loadRewardVideoAd(adVideoSlot, object : RewardVideoAdListenerAdapter() {

            override fun onRewardVideoAdLoad(p0: TTRewardVideoAd?) {

                p0?.setRewardAdInteractionListener(object : RewardAdInteractionListenerAdapter() {

                    var startTime: Long = 0L

                    override fun onRewardVerify(p0: Boolean, p1: Int, p2: String?) {

                    }

                    override fun onVideoComplete() {

                    }

                    override fun onAdShow() {
                        startTime = SystemClock.elapsedRealtime()
                    }

                    override fun onAdClose() {

                        withdraw(cash, isAlipay)
                    }

                })

                p0?.showRewardVideoAd(this@WithDrawActivity2)
            }

            override fun onError(p0: Int, p1: String?) {
                withdraw(cash, isAlipay)
                p1?.apply {
                    Toaster.message(this)
                }
            }

        })
    }

    private fun withdraw(cash: String, alipay: Boolean) {
        if (alipay)
            withDrawPresenter.withdrawAlipay(cash, "")
        else withDrawPresenter.withdrawWx(cash, "")
    }

    override fun onWithDraw(body: WithDrawBody) {
        viewModel.loadBalance()
        SimpleDialogBuilder()
                .title("申请提现成功")
                .titleTextColor(R.color.colorPrimary)
                .buttonText("我知道了")
                .onButtonClick(View.OnClickListener {
                    quickStartActivity(DetailsActivity::class.java)
                })
                .content("成功申请提现${body.successNum}元，请耐心等待到账")
                .build(this)
                .show()
    }

    override fun onError(t: Throwable) {
        viewModel.load()
        super.onError(t)
    }

    override fun onSupportNavigateUp(): Boolean {
        onBackPressed()
        return super.onSupportNavigateUp()
    }
}
